/**
 * Project Name:javaBaseReview
 * Package Name:com.xuwei.base.thread
 * author:David
 * Date:2015年8月19日下午8:45:46
 * Copyright (c) 2015, xw123box@126.com All Rights Reserved.
 *
 */
package com.xuwei.base.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * @author David
 * @since 2015年8月19日 下午8:45:46
 * @version 
 * @since JDK 1.6
 */
public class ConditionCommunication {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final Buisiness buisiness=new Buisiness();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(int i=1;i<=50;i++){
					buisiness.sub(i);
				}
				
			}
		}).start();
		
		for(int i=1;i<=50;i++){
			buisiness.main(i);
		}
		
	}
	
	
	static class Buisiness{
		Lock lock=new ReentrantLock();
		Condition condition=lock.newCondition();
		private boolean bShouldSub=true;
		public void sub(int i){
			lock.lock();
			try{
				while(!bShouldSub){
					try {
						condition.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				for(int j=1;j<=10;j++){
					System.out.println("sub thread sequence of "+j+",loop of "+i);
				}
				bShouldSub=false;
				condition.signal();
			}finally{
				lock.unlock();
			}
		}
		
		public  void main(int j){
			lock.lock();
			try{
				while(bShouldSub){
					try {
						condition.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				for(int i=1;i<=100;i++){
					System.out.println("main thread sequence of "+i+",loop of"+j);
				}	
				bShouldSub=true;
				condition.signal();
			}finally{
				lock.unlock();
			}
		}
		
		
	}

}



